import React, {PropsWithChildren, useEffect, useMemo, useState} from 'react'
import {ScrollView, Text, View} from "@tarojs/components";
import {observer} from "mobx-react";
import procurementReceiptPageStackStore from "../store/ProcurementReceiptPageStackStore";
import Scaffold from "../components/Scaffold";
import {Button, Cell, SearchBar, Space, Tag} from "@nutui/nutui-react-taro";
import {
    ProcurementReceiptItem,
    validateProcurementReceiptItem,
    validateProcurementReceiptItemSub
} from "../apis/ProcurementReceiptApi";
import InputNumberPrompt from "../components/InputNumberPrompt";
import {useMyNavigationBarHeight} from "../components/MyNavigationBar";

export interface ProcurementReceiptValidateProps extends PropsWithChildren {

}

const ProcurementReceiptValidate: React.FC<ProcurementReceiptValidateProps> = ({}) => {
    const data = procurementReceiptPageStackStore.detail!
    const list = data.items
    const [keyword, setKeyword] = useState("")
    const scrollToTargetId = useMemo(() => {
        if (!!keyword) {
            let target = list.find(item =>
                item.name.toLowerCase().includes(keyword.toLowerCase())
                || item.barcode.toLowerCase().includes(keyword.toLowerCase())
                || item.subGoods?.name.toLowerCase().includes(keyword.toLowerCase())
                || item.subGoods?.number.toLowerCase().includes(keyword.toLowerCase())
            );
            if (target){
                return `item${[target.id,target.subGoods?.id].filter(it=>!!it).join("-")}`
            }
        }
        return undefined
    }, [keyword,list]);
    let myNavigationBarHeight = useMyNavigationBarHeight();
    return <>
        <Scaffold title={data.supplier.name + "入库单验货" + keyword}>
            <SearchBar onChange={setKeyword} placeholder={"搜索并跳转到指定货品"}/>
            <ScrollView scrollY style={{position: "relative",height:`calc(100vh - ${myNavigationBarHeight}px - 44px)`}} scrollIntoView={scrollToTargetId}>
                <View>
                    {
                        list.map((item, index) => {
                            return <ProcurementReceiptValidateItem data={item} onValidate={async v => {
                                if (item.subGoods) {
                                    await validateProcurementReceiptItemSub(data.id, item.id, item.subGoods.id, {amount: v})
                                } else {
                                    await validateProcurementReceiptItem(data.id, item.id, {amount: v})
                                }
                                data.items[index].practicalAmount = v
                                procurementReceiptPageStackStore.updateDetail({
                                    ...data,
                                    items: Array.from(data.items),
                                })
                            }}/>
                        })
                    }
                </View>
            </ScrollView>
        </Scaffold>
    </>
}

export default observer(ProcurementReceiptValidate)


const ProcurementReceiptValidateItem: React.FC<{
    data: ProcurementReceiptItem,
    onValidate: (amount: number) => Promise<void>
}> = (props) => {
    const data = props.data
    let basicUnit = data.units.find(it => it.basicMultiple === 0);
    const unit = data.unit ? data.units.find(it => it.id === data.unit?.id) : basicUnit
    const amountString = !unit || unit.id === basicUnit?.id ? `${data.amountInOrder}${unit?.name}` : `${data.amountInOrder}${unit.name}=${data.amountInOrder * unit.basicMultiple}${basicUnit?.name}`
    const [loading, setLoading] = useState(false)
    const [amountPromptVisible, setAmountPromptVisible] = useState(false)

    async function validate(amount: number) {
        setLoading(true)
        try {
            await props.onValidate(amount)
        } finally {
            setLoading(false)
        }

    }

    const validated = useMemo(() => {
        return data.amountInOrder * (unit?.basicMultiple || 1) === data.practicalAmount
    }, [data.amountInOrder, unit, data.practicalAmount]);
    return <Cell id={`item${[data.id,data.subGoods?.id].filter(it=>!!it).join("-")}`} title={data.subGoods ? data.subGoods.name + `（${data.name}）` : data.name}
                 description={
                     <Space direction={"vertical"}>
                         <Text>{data.subGoods ? data.barcode + "|" + data.subGoods.number : data.barcode}</Text>
                         <Space justify={"between"} align={"center"}>
                             <Text>{amountString}</Text>
                             {<Space justify={"end"} align={"center"}>
                                 {!validated && !!data.practicalAmount &&
                                     <Text>已验收{data.practicalAmount}{basicUnit?.name}</Text>}
                                 <Button size={"small"} type={"primary"} fill={"outline"} loading={loading}

                                         onClick={() => {
                                             setAmountPromptVisible(true)
                                         }}>少货</Button>
                                 {!validated ?
                                     <Button size={"small"} type={"primary"} loading={loading} onClick={async () => {
                                         await validate(data.amountInOrder * (unit?.basicMultiple || 1))
                                     }}>收货{data.amountInOrder}{unit?.name}</Button> :
                                     <Tag type={"success"}>已验收</Tag>}
                             </Space>}
                         </Space>
                         {amountPromptVisible &&
                             <InputNumberPrompt initialValue={data.amountInOrder} onConfirm={async value => {
                                 await validate(value)
                             }} visible={amountPromptVisible} onCancel={() => setAmountPromptVisible(false)}
                                                title={`请输入验收数量${basicUnit ? `（单位：${basicUnit.name}）` : ""}`}/>}
                     </Space>
                 }>

    </Cell>
}
